import React, { useState, useEffect } from "react";
import { Modal, Table, Button, Alert, Typography } from "antd";
import type { ColumnsType } from "antd/es/table";
import { FlightOption } from "../../services/apiService";
import { useTranslation } from 'react-i18next';

const { Text } = Typography;

interface CachedFlightSelectionModalProps {
  visible: boolean;
  flights: FlightOption[];
  onCancel: () => void;
  onSelect: (flightInfo: any) => void;
}

const CachedFlightSelectionModal: React.FC<CachedFlightSelectionModalProps> = ({
  visible,
  flights,
  onCancel,
  onSelect,
}) => {
  const { t } = useTranslation();
  const [selectedFlight, setSelectedFlight] = useState<FlightOption | null>(
    null,
  );
  const [isProcessing, setIsProcessing] = useState(false);

  useEffect(() => {
    if (visible) {
      loadCachedFlights();
    }
  }, [visible]);

  const loadCachedFlights = () => {
  };

  const handleSelectFlight = async () => {
    if (selectedFlight) {
      setIsProcessing(true);
      try {
        await onSelect(selectedFlight);
        setSelectedFlight(null);
      } catch (error) {
        console.error(t('cachedFlightModal.flightSelectionFailed'), error);
      } finally {
        setIsProcessing(false);
      }
    }
  };

  const columns: ColumnsType<FlightOption> = [
    {
      title: t('cachedFlightModal.outboundFlight'),
      key: "outbound",
      render: (_, record) => (
        <div>
          <div>
            <strong>{record.outboundFlight.flightNumber}</strong> -{" "}
            {record.outboundFlight.airline}
          </div>
          <div>
            {record.outboundFlight.departureCity} →{" "}
            {record.outboundFlight.arrivalCity}
          </div>
          <div>
            {record.outboundFlight.departureTime} -{" "}
            {record.outboundFlight.arrivalTime}
          </div>
          <div>{t('cachedFlightModal.flightDuration')}: {record.outboundFlight.duration}</div>
        </div>
      ),
    },
    {
      title: t('cachedFlightModal.returnFlight'),
      key: "return",
      render: (_, record) => (
        <div>
          <div>
            <strong>{record.returnFlight.flightNumber}</strong> -{" "}
            {record.returnFlight.airline}
          </div>
          <div>
            {record.returnFlight.departureCity} →{" "}
            {record.returnFlight.arrivalCity}
          </div>
          <div>
            {record.returnFlight.departureTime} -{" "}
            {record.returnFlight.arrivalTime}
          </div>
          <div>{t('cachedFlightModal.flightDuration')}: {record.returnFlight.duration}</div>
        </div>
      ),
    },
  ];

  return (
    <Modal
      title={t('cachedFlightModal.title')}
      closable={false}
      maskClosable={!isProcessing}
      open={visible}
      onCancel={onCancel}
      width={1000}
      footer={[
        <Button key="cancel" onClick={onCancel} disabled={isProcessing}>
          {t('cachedFlightModal.cancel')}
        </Button>,
        <Button
          key="select"
          type="primary"
          disabled={!selectedFlight || isProcessing}
          loading={isProcessing}
          onClick={handleSelectFlight}
        >
          {isProcessing ? t('cachedFlightModal.processing') : t('cachedFlightModal.selectFlight')}
        </Button>,
      ]}
    >
      {flights.length === 0 ? (
        <Alert
          message={t('cachedFlightModal.noCachedData')}
          description={t('cachedFlightModal.noCachedDataDesc')}
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      ) : (
        <>
          <Alert
            message={t('cachedFlightModal.usingCachedData')}
            description={t('cachedFlightModal.foundFlights', { count: flights.length })}
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <Table
            columns={columns}
            dataSource={flights}
            rowKey={(record) =>
              `${record.outboundFlight.flightNumber}_${record.returnFlight.flightNumber}`
            }
            pagination={{ pageSize: 25 }}
            rowSelection={{
              type: "radio",
              selectedRowKeys: selectedFlight
                ? [
                    selectedFlight.outboundFlight.flightNumber +
                      "_" +
                      selectedFlight.returnFlight.flightNumber,
                  ]
                : [],
              onChange: (_, selectedRows) => {
                if (!isProcessing) {
                  setSelectedFlight(selectedRows[0] || null);
                }
              },
            }}
            scroll={{ y: 400 }}
            loading={isProcessing}
          />
        </>
      )}
    </Modal>
  );
};

export default CachedFlightSelectionModal;
